import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp(); // 获取 HTTP 上下文
    const response = ctx.getResponse(); // 获取 HTTP 响应对象

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR; // 非 HttpException 异常，默认状态码为 500

    const message =
      exception instanceof HttpException
        ? exception.getResponse()
        : 'Internal server error'; // 非 HttpException 异常，默认消息为 'Internal server error'

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      message,
    }); // 返回 JSON 格式的响应体
  }
}